import errorCode from '@/utils/errorCode'
import { getToken } from '@/utils/auth'

let timeout = 10000
const baseUrl = getApp().globalData.config.baseUrl

const request = config => {
	// 是否需要设置 token
	const isToken = (config.headers || {}).isToken === false
	config.header = config.header || {}
	if (getToken() && !isToken) {
	  config.header['Authorization'] = getToken()
	}
	return new Promise((resolve, reject) => {
		if(config.loading) uni.showLoading({title: '上传中'})
		uni.uploadFile({
			timeout: config.timeout || timeout,
			url: baseUrl + config.url,
			filePath: config.filePath,
			name: config.name || 'file',
			header: config.header,
			formData: config.formData,
			success: (res) => {
				if(config.loading) uni.hideLoading()
				let result = JSON.parse(res.data)
				const code = result.code || 200
				const msg = errorCode[code] || result.msg || errorCode['default']
				if (code === 200) {
					resolve(result)
				} else if (code !== 200) {
					uni.showToast({
						icon: 'none',
						title: msg
					})
					reject(code)
				}
			},
			fail: (error) => {
				if(config.loading) uni.hideLoading()
				let { errMsg } = error
				if (errMsg == 'Network Error') {
					errMsg = '后端接口连接异常'
				} else if (errMsg.includes('timeout')) {
					errMsg = '系统接口请求超时'
				} else if (errMsg.includes('Request failed with status code')) {
					errMsg = '系统接口' + errMsg.substr(errMsg.length - 3) + '异常'
				}
				uni.showToast({
					icon: 'none',
					title: errMsg
				})
				reject(error)
			}
		})
	})
}

export default request